package com.wzh.glsc.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.wzh.common.constant.AuthServerConstant;
import com.wzh.common.utils.R;
import com.wzh.common.vo.MemberVo;
import com.wzh.glsc.auth.feign.MemberFeignService;
import com.wzh.glsc.auth.service.LoginService;
import com.wzh.glsc.auth.vo.UserLoginVo;
import com.wzh.glsc.auth.vo.UserRegistVo;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xiaoming
 * @PackageName:com.wzh.glsc.auth.web
 * @ClassName:@{NAME}
 * @Description:
 * @date:@{DATE}@{TIME}
 */
@Controller
public class LoginController {

    @Resource
    LoginService loginService;
    @Resource
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam String phone) {
       return loginService.sendCode(phone);
    }


    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        if(session.getAttribute(AuthServerConstant.LOGIN_USEER)!=null){
            return "redirect:http://gulimall.com";
        }
        return "login";
    }

    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession session) {
        R r = memberFeignService.login(userLoginVo);
        if(r.getCode()!=0){
            Map<String,String> map=new HashMap<>();
//            map.put("msg", r.getData(new TypeReference<String>(){}));
            map.put("msg", r.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",map);
            return "redirect:http://auth.gulimall.com/login.html";
        }
        Map<String,MemberVo> data = r.getData("data", new TypeReference<Map<String,MemberVo>>() {
        });
        session.setAttribute(AuthServerConstant.LOGIN_USEER,data.get("data"));
        return "redirect:http://gulimall.com";
    }

    //RedirectAttributes 用于重定向 带上转发的数据。模拟session
    //只要跳到下一个页面取出来后，session就会删除
    //TODO 分布式下的session问题
    @PostMapping("/register")
    public String register(@Validated UserRegistVo userRegistVo,
                           BindingResult bindingResult,
                           RedirectAttributes redirectAttributes) {
        //bindingResult 是校验的后返回的对象
        //判断数据校验是否合格、有错误
        if(bindingResult.hasErrors()){
            //把出错的属性收集成一个map返回给页面
            Map<String, String> collect = bindingResult.getFieldErrors().stream().collect(
                    Collectors.toMap((fieId) -> {
                        //出错的属性 这里可以 简写成  FieldError::getField FieldError是fieId的类
                        return fieId.getField();
                    }, (fieId) -> {
                        //出错的属性设置的message
                        return fieId.getDefaultMessage();
                    },(s1,s2)->s2));
            //带上一个一闪而过的数据
            redirectAttributes.addFlashAttribute("errors",collect);
//            return "reg";
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //验证码不对或者失效时
        if(!loginService.codeRight(userRegistVo)){
            Map<String, String> collect=new HashMap<>();
            collect.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",collect );
        }
        //注册
        R register = loginService.register(userRegistVo);
        if(register.getCode()!=0){
            Map<String, String> collect=new HashMap<>();
            collect.put("msg", register.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",collect );
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }
}
